<template>
  <div class="pager">
    <van-nav-bar
      :title="pageData.title"
      right-text="刷新"
      fixed
      left-arrow
      @click-left="mapMethod.onClickLeft"
      @click-right="mapMethod.onClickRight"
    />
    <div class="maps order-maps" :id="pageData.ids"></div>
    <div class="info info-box" v-if="pageData.showMode">
      <div class="info-cont">
        <!--        呼叫车辆中-->
        <div class="call-car" v-if="pageData.showMode == '1'">
          <div class="cont-box">
            <div class="left">
              <p>正在派车， 请耐心等待</p>
              <span>正在为您查询司机车辆，请您耐心等待</span>
            </div>
            <div class="right">
              <img :src="pageData.img.waitCar" alt="等待中" />
            </div>
          </div>
          <div class="btn" @click="mapMethod.cancelOrder">
            <van-icon name="clear" />
            <p>取消订单</p>
          </div>
        </div>
        <!--        车已经叫到，等待司机到达-->
        <div class="wait-car" v-else>
          <div class="top">
            <template
              v-if="pageData.showMode == '2' || pageData.showMode == '2_1'"
            >
              <p v-show="pageData.showMode == '2'">
                司机即将到达，请避开人群等待
              </p>
              <p v-show="pageData.showMode == '2_1'">司机已到达，待上车</p>
              <span>
                请前往<span class="oranges">
                  {{ pageData.orderDetail.depart_place }}
                  <!--                双井街道优仕阁大厦B座--> </span
                >上车。<template v-if="pageData.showMode == '2'"
                  >请提前到路边等候，</template
                >戴好口罩，安全出行
              </span>
            </template>
            <template v-else-if="pageData.showMode == '3'">
              <p>正在前往目的地</p>
              <span>正在前往目的地，请您系好安全带，佩戴口罩，安全出行</span>
            </template>
            <template
              v-else-if="pageData.showMode == '4' || pageData.showMode == '99'"
            >
              <p>行程已结束</p>
              <span v-if="pageData.showMode == '99'"
                >您的行程已结束，欢迎下次预订。</span
              >
              <span v-else
                >您的行程已结束，欢迎下次预订，若订单未支付，请尽快支付，避免影响下次用车</span
              >
            </template>
            <template
              v-else-if="pageData.showMode == '5' || pageData.showMode == '5_1'"
            >
              <p>订单已取消</p>
              <span v-if="pageData.showMode == '5'"
                >订单已取消，若需用车，请重新预订。</span
              >
              <span v-else
                >订单已取消，若产生手续费，请尽快支付，避免影响下次用车</span
              >
            </template>
          </div>
          <div class="cont-box">
            <div class="left">
              <p>
                <!--                京A62843-->
                {{ pageData.detail.vehicle_no }}
              </p>
              <span>
                <!--                丰田卡罗拉双擎 • 白色-->
                {{ pageData.detail.vehicle_color
                }}<span v-show="pageData.detail.vehicle_color">●</span
                >{{ pageData.detail.vehicle_model }}
              </span>
              <div class="driver-info">
                {{ pageData.detail.driver_name }}
                <template v-if="pageData.detail.driver_level">
                  &nbsp; <van-icon name="star" color="#FFD408" />
                  {{ Number(pageData.detail.driver_level).toFixed(1) }}
                </template>
                <!--                {{ pageData.detail.driver_phone }}-->
                <!--                4568单-->
              </div>
            </div>
            <div class="right">
              <img
                class="carimg"
                v-if="pageData.detail.car_model_image"
                :src="pageData.detail.car_model_image"
                alt=""
              />
              <img
                class="carimg"
                v-else
                :src="pageData.img.waitCar"
                alt="等待中"
              />
              <img
                v-if="pageData.detail.driver_avatar"
                class="driverimg"
                :src="pageData.detail.driver_avatar"
                alt=""
              />
            </div>
          </div>
          <div
            class="btn"
            v-if="pageData.showMode == '2' || pageData.showMode == '2_1'"
          >
            <div class="btn-left" @click="mapMethod.cancelOrder">
              <van-icon name="clear" />
              <p>取消订单</p>
            </div>
            <div class="btn-right">
              <van-icon name="phone" />
              <p @click="mapMethod.openPhone">打电话</p>
            </div>
          </div>
          <div
            v-else-if="pageData.showMode == '4' || pageData.showMode == '5_1'"
            class="btn pay-btn"
            @click="mapMethod.pay()"
          >
            <van-icon name="gold-coin" />
            <p>支付</p>
          </div>
          <!--          投诉与评价这期不做的-->
          <!--          <div class="btn" v-else>-->
          <!--            <div class="btn-left">-->
          <!--              <van-icon name="clear" />-->
          <!--              <p>评价</p>-->
          <!--            </div>-->
          <!--            <div class="btn-right">-->
          <!--              <van-icon name="phone" />-->
          <!--              <p>投诉</p>-->
          <!--            </div>-->
          <!--          </div>-->
        </div>
      </div>
    </div>
    <van-popup v-model:show="pageData.popup_show" round>
      <div class="close_order_contents">
        <div class="close_title">选择取消原因</div>
        <p class="info-warning">取消可能会产生手续费，请确认</p>
        <div class="close_reason">
          <div
            v-for="(item, index) in pageData.close_reason"
            :key="index + item.reason"
            class="_reason_item"
            @click="mapMethod.click_reason_item(item, index)"
            :class="{ click_style: item.show, only_style: item.only_style }"
          >
            {{ item.reason }}
          </div>
        </div>
        <div class="close_button">
          <div class="_button_close" @click="mapMethod._button_close">取消</div>
          <div class="_button_sure" @click="mapMethod._button_sure">确定</div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import {
  getCurrentInstance,
  onMounted,
  reactive,
  onBeforeUnmount,
  watch,
  ref
} from "vue";
import { initMapSmall } from "/@/assets/map/searchCarMap/map-config.js";
import waitCar from "/@/assets/img/waitCar.png";
import carImg from "/@/assets/img/carImg.png";
import { Dialog, Toast } from "vant";
import {
  driving,
  drivingClear
} from "/@/assets/map/searchCarMap/getMapData.js";

const { proxy } = getCurrentInstance();
onMounted(() => {
  if (!proxy.$route.query.order_id) {
    // 如果没用order_id则不可以进来
    Dialog.alert({
      message: "请传入订单编号"
    }).then(async () => {
      mapMethod.onClickLeft();
    });
    return;
  }
  mapMethod.getDetail();
  mapMethod.initMap();
});
onBeforeUnmount(() => {
  mapMethod.clearRepeatGetData();
});
const pageData = reactive({
  ids: `map-container${new Date().getTime()}`,
  popup_show: false,
  cancel_reason: "",
  close_reason: [
    { reason: "行程有变，不需要用车了" },
    { reason: "发错订单" },
    { reason: "平台派单太远" },
    { reason: "司机找不到上车位置" },
    { reason: "车辆信息与订单显示不符" },
    { reason: "其他", only_style: true }
  ],
  title: "等待司机接单",
  orderDetail: {},
  detail: {
    driver_name: ""
  },
  showMode: "", // 1：等待司机接单， 2：待出发, 2_1: 待上车， 3：行程中， 4：行程结束，待支付，5: 取消，5_1：取消待支付 99：行程结束只展示详情
  img: {
    waitCar
  }
});
// {
//   "driver_name": "王师傅",
//     "driver_phone": "18410974477",
//     "driver_phone_virtual": null,
//     "vehicle_model": "奥迪A7（进口）",
//     "vehicle_color": "黑",
//     "vehicle_no": "京I61114",
//     "driver_level": "4",
//     "driver_avatar": null,
//     "current_dlat": "38.899929",
//     "current_dlng": "121.519882",
//     "order_status": "4",
//     "amap_order_status": "7"
// }

const mapData = reactive({
  AMap: null,
  AMapUI: null,
  map: null
});

let timer = null; // 定时器
let phase = 15000; // 刷新时间段

let pageIndex = ref(0);

let startMarker, endMarker, mineMarker;

// 地图和详情加载完了之后来干这个事
watch(
  () => pageIndex.value,
  item => {
    if (item === 2) {
      if (["4", "99", "5", "5_1"].includes(item)) {
        mapMethod.clearMarker();
        mapMethod.drivingMap();
      } else {
        mapMethod.setPos();
      }
    }
  },
  { immediate: true }
);
// 地图和详情加载完了之后来干这个事
watch(
  () => pageData.showMode,
  item => {
    try {
      if (["4", "99"].includes(item)) {
        mapMethod.clearMarker();
        mapMethod.drivingMap();
      } else {
        mapMethod.setPos();
      }
    } catch (e) {}
  },
  { immediate: true }
);

const mapMethod = {
  getLatLng() {
    // 地图绘制
    const car = pageData.orderDetail.car_info_list || [],
      pos = car[0] || {};
    const from = {
        flat: pos.start_lat,
        flng: pos.start_lng
      },
      to = {
        flat: pos.end_lat,
        flng: pos.end_lng
      };
    return {
      from,
      to
    };
  },
  drivingMap() {
    const { from, to } = mapMethod.getLatLng();
    try {
      setTimeout(() => {
        drivingClear();
        if (from.flng && from.flat && to.flng && to.flat)
          driving(from, to, true);
      }, 1000);
    } catch (e) {}
  },
  setPos() {
    // 设置起点和终点
    mapMethod.clearMarker();
    const { from, to } = mapMethod.getLatLng();
    try {
      startMarker = new window.AMap.Marker({
        position: new window.AMap.LngLat(from.flng, from.flat),
        icon: "https://webapi.amap.com/theme/v1.3/markers/n/start.png",
        map: window.MAPINSTANCE
      });

      endMarker = new window.AMap.Marker({
        position: new window.AMap.LngLat(to.flng, to.flat),
        icon: "https://webapi.amap.com/theme/v1.3/markers/n/end.png",
        map: window.MAPINSTANCE
      });
      // 调整视野达到最佳显示区域
      window.MAPINSTANCE.setFitView([startMarker, endMarker]);
    } catch (e) {}
  },
  clearMineMarker() {
    mineMarker &&
      window.MAPINSTANCE &&
      window.MAPINSTANCE.remove &&
      window.MAPINSTANCE.remove(mineMarker);
  },
  setMine(data) {
    try {
      mapMethod.clearMineMarker();
      mineMarker = new window.AMap.Marker({
        position: new window.AMap.LngLat(data.lng, data.lat),
        content: `<img src="${carImg}" style="width:36px;height:36px"/>`,
        map: window.MAPINSTANCE
      });
    } catch (e) {}
  },
  clearMarker() {
    try {
      window.MAPINSTANCE.remove(startMarker);
      window.MAPINSTANCE.remove(endMarker);
    } catch (e) {}
  },
  initMap() {
    initMapSmall(pageData.ids, [], { noMinePos: true })
      .then(({ AMap, AMapUI, map }) => {
        pageIndex.value++;
        mapData.AMap = AMap;
        mapData.AMapUI = AMapUI;
        mapData.map = map;
        mapMethod.setMinePos();
      })
      .catch(err => {
        console.log(err);
      });
  },
  async getDetail() {
    const res = await proxy.$axiosJson("/security/car/queryOrderDetail", {
      order_id: proxy.$route.query.order_id,
      member_id: localStorage.memberId
    });
    pageIndex.value++;
    pageData.orderDetail = res.data || {};
    const status = ["4", "7", "8", "9"];
    mapMethod.orderTypeChange(pageData.orderDetail.amap_order_status);
    mapMethod.repeatGetData();
    if (status.includes(pageData.orderDetail.amap_order_status)) {
      mapMethod.clearRepeatGetData();
    }
  },
  repeatGetData() {
    mapMethod.getDrivers();
    timer = window.setInterval(() => {
      mapMethod.getDrivers();
    }, phase);
  },
  clearRepeatGetData() {
    window.clearInterval(timer);
  },
  async getDrivers() {
    const query = {
      order_id: proxy.$route.query.order_id
    };
    const res = await proxy.$axiosJson(
      "/security/v1/icardcOrder/queryDriverInfo",
      query
    );
    if (res.biz_result === "SUCCESS" && res.ret_code === "10000") {
      pageData.detail = res.data || {};
      mapMethod.orderTypeChange(pageData.detail.amap_order_status);
      const lnglat = {
        lat: pageData.detail.current_dlat,
        lng: pageData.detail.current_dlng
      };
      const status = ["7", "8", "9"];
      if (
        lnglat.lat &&
        lnglat.lng &&
        status.includes(pageData.detail.amap_order_status)
      ) {
        mapMethod.setMine(lnglat);
      }
    } else {
      Toast(res.ret_msg || "获取详情失败");
    }
  },
  setMinePos() {
    // 设置地图上”定位小圆点“的位置
    try {
      const p = document.querySelector(".order-maps"),
        mine = p.querySelector(".amap-geolocation"),
        box = document.querySelector(".info-box"),
        h = box.offsetHeight;
      if (mine) {
        mine.style.bottom = h + 15 + "px";
      }
    } catch (e) {}
  },
  onClickLeft() {
    const query = proxy.$route.query;
    if (query.app_car_detail == "1" && query.isNative == "1") {
      JSBridge.call("popWindow");
      return false;
    }
    if (query.create_order) {
      proxy.$router.push({
        path: "/home"
      });
      return;
    }
    proxy.$router.back();
  },
  onClickRight() {
    mapMethod.clearRepeatGetData();
    mapMethod.repeatGetData();
  },
  orderTypeChange(type) {
    const is = list => list.includes(type);
    // 设置标题
    const obj = {
      "4": "等待司机接单",
      "7": "等待司机到达",
      "8": "车辆已到达，待上车",
      "9": "行程中",
      "5": "服务结束，待⽀付",
      "1": "订单结束"
    };
    pageData.title = obj[type] || "订单详情";
    // 根据状态设置显示的内容
    if (is(["4"])) {
      pageData.showMode = "1";
    } else if (is(["7", "8"])) {
      pageData.showMode = "2";
      if (type == "8") pageData.showMode = "2_1";
    } else if (is(["9"])) {
      pageData.showMode = "3";
    } else if (is(["5"])) {
      pageData.showMode = "4";
      mapMethod.clearRepeatGetData();
      mapMethod.clearMineMarker();
    } else if (is(["10", "3"])) {
      pageData.showMode = "5";
      if (type == "3") pageData.showMode = "5_1";
      mapMethod.clearRepeatGetData();
      mapMethod.clearMineMarker();
    } else {
      pageData.showMode = "99";
      mapMethod.clearRepeatGetData();
      mapMethod.clearMineMarker();
    }
    mapMethod.setMinePos();
  },
  cancelOrder() {
    pageData.popup_show = true;
    mapMethod.clearRepeatGetData();
  },
  // 点击 -> 取消原因
  click_reason_item(item, index) {
    pageData.close_reason.forEach((ooo, num) => {
      ooo.show = false;
    });
    pageData.close_reason[index].show = !item.show;
    pageData.cancel_reason = item.reason;
  },
  // 取消 -> 取消原因
  _button_close() {
    pageData.popup_show = false;
    mapMethod.repeatGetData();
  },
  // 确定 -> 取消原因
  async _button_sure() {
    const url = "/security/v1/icardcOrder/cancelOrder";
    const data = {
      order_id: proxy.$route.query.order_id,
      cancel_reason: pageData.cancel_reason
    };
    try {
      const res = await proxy.$axiosJson(url, data);
      if (res.ret_code == 10000) {
        mapMethod._button_close();
      }
    } catch (err) {}
  },
  openPhone() {
    // 拨打电话
    const phone = pageData.detail.driver_phone;
    if (!phone) {
      Toast("电话号码不存在");
      return;
    }
    window.location.href = `tel:${phone}`;
  },
  pay() {
    if (sessionStorage.isNative == "1") {
      JSBridge.call("goCarPay", {
        order_id: proxy.$route.query.order_id
      });
      return false;
    }
    proxy.$router.push({
      path: "/CarCashier",
      query: {
        order_id: proxy.$route.query.order_id
      }
    });
  }
};
// 正常流程：
// 4:派单中
// 7：待出发（司机还没到上车目的地）
// 8：待上⻋（司机来了  乘客没上车）
// 9：⾏程中
// 5:订单完成待⽀付
// 1：订单完成;
//
//
// 其他流程：
// 流程1：
// 3；订单取消待支付（可能存在违约金才会用此状态）
// 6：关 闭（订单已经取消 成为关闭状态）
//
// 流程2：
//  11.退订申请中
// 12.待退款
// 10.已退订
</script>

<style lang="less" scoped>
:deep(.amap-copyright),
:deep(.amap-logo) {
  z-index: 0;
  display: none !important;
}
.oranges {
  color: #ff9b1b !important;
}
.pager {
  width: 100%;
  height: 100%;
  position: relative;
  .maps {
    width: 100%;
    height: 100%;
  }
  .info {
    position: absolute;
    bottom: 0;
    background: transparent;
    padding: 0px 7px 15px 7px;
    width: 100%;
    z-index: 500;
    .info-cont {
      background: #ffffff;
      border-radius: 7px;
      font-size: 14px;
      overflow: hidden;
    }
  }
}
// 呼叫汽车中
.call-car {
  color: #333333;
  .cont-box {
    padding: 10px;
    overflow: hidden;
    .right {
      width: 70px;
      height: 70px;
      float: left;
    }

    .left {
      width: calc(100% - 70px);
      float: left;

      p {
        font-size: 18px;
        font-weight: 600;
        margin-top: 10px;
        margin-bottom: 10px;
      }

      span {
        font-size: 12px;
        color: #666666;
      }
    }
  }
  .btn {
    clear: both;
    text-align: center;
    padding: 7px 0px;
    border-top: 1px solid #eeeeee;
    color: #333333;
    font-size: 13px;
    p {
      text-align: center;
      padding-top: 5px;
    }
    :deep(i) {
      font-size: 20px;
      color: #666666;
    }
  }
}
//等待车辆到达
.wait-car {
  color: #333333;
  .top {
    margin-bottom: 10px;
    padding: 0 10px;
    p {
      font-size: 18px;
      font-weight: 600;
      margin-top: 10px;
      margin-bottom: 10px;
    }
    span {
      font-size: 12px;
      color: #666666;
    }
  }
  .cont-box {
    padding: 10px;
    overflow: hidden;
    .right {
      width: 125px;
      height: 72px;
      line-height: 72px;
      text-align: right;
      vertical-align: middle;
      float: left;
      position: relative;
      .carimg {
        vertical-align: middle;
        max-width: 100%;
        max-height: 100%;
      }
      .driverimg {
        width: 36px;
        height: 36px;
        position: absolute;
        right: 0;
        bottom: 0;
        border-radius: 50%;
      }
    }
    .left {
      width: calc(100% - 125px);
      float: left;
      p {
        font-size: 28px;
        font-weight: 600;
        margin-bottom: 10px;
      }
      span {
        font-size: 14px;
        font-weight: bold;
      }
      .driver-info {
        color: #6b6b6b;
        margin: 10px 0;
      }
    }
  }
  .btn {
    clear: both;
    padding: 7px 0px;
    border-top: 1px solid #eeeeee;
    overflow: hidden;
    &:after {
      content: "";
      clear: both;
    }
    & > div {
      width: 50%;
      float: left;
      text-align: center;
      color: #333333;
      font-size: 13px;
    }
    & > div:first-child {
      border-right: 1px solid #eeeeee;
    }
    p {
      text-align: center;
      padding-top: 5px;
    }
    :deep(i) {
      font-size: 20px;
      color: #666666;
    }
  }
  .pay-btn {
    text-align: center;
    background: #ff8d02;
    color: #ffffff;
    padding: 7px 0;
    p {
      text-align: center;
      padding-top: 5px;
    }
    :deep(i) {
      color: #ffffff;
    }
  }
}
//取消
.close_order_contents {
  width: 310px;
  padding: 20px 28px;
  .close_title {
    width: 100%;
    text-align: center;
    font-size: 16px;
    font-weight: 600;
    color: #333333;
    line-height: 16px;
  }
  .close_reason {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 8px;
    ._reason_item {
      background: #f6f6f6;
      border-radius: 4px;
      margin-right: 8px;
      margin-bottom: 8px;
      padding: 7px 8px 6px 10px;
      font-size: 14px;
      font-weight: 500;
      color: #7c7b7b;
      line-height: 14px;
    }
    ._reason_item:nth-child(2n) {
      margin-right: 0;
    }
    :deep(.click_style) {
      background: #e5f2ff;
      color: #208cff;
    }
    :deep(.only_style) {
      padding: 7px 22px 6px 22px;
    }
  }
  .close_button {
    display: flex;
    font-size: 14px;
    font-weight: 500;
    line-height: 14px;
    div {
      width: 116px;
      height: 41px;
      border-radius: 6px;
      line-height: 41px;
      text-align: center;
    }
    ._button_close {
      background: #f5f5f5;
      color: #666666;
      margin-right: 19px;
    }
    ._button_sure {
      background: #208cff;
      color: #ffffff;
    }
  }
}
.info-warning {
  color: #e6a23c;
  padding: 10px 0;
  line-height: 25px;
  font-size: 14px;
}
</style>
